package zho.remotecontrol.text;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.sql.Time;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import zho.remotecontrol.R;
import zho.remotecontrol.Util.Utility;
import zho.remotecontrol.socket.SocketClient;

public class Main extends AppCompatActivity {
    public static final String IP = "120.78.70.3";
//    public static final String IP = "192.168.115.2";
    public static final int PORT = 6567;

    public static final int BUTTON_ON = 1;
    public static final int BUTTON_OFF = 0;
    public int button_mode;
    public static Socket socket;
    //——————改为统一一个client
    //注意更改register和powerBtn监听器
    public SocketClient client;
    int socket_mode;
    TranslateAnimation mShowAction;
    TranslateAnimation mHiddenAction;
    TranslateAnimation mShowAction2;
    Button connect;
    Button close_connect;
    Button open_delay;
    Button login;
    LinearLayout connect_console;
    LinearLayout connected_console;
    LinearLayout device_console;
    Toolbar toolbar;
    Button bt_search;

    //数据输入
    EditText ed_searchId;
    EditText userNameEdit;
    EditText userPasswordEdit;
    EditText delay_time;
    //对应的数据信息显示
    TextView device_ID;
    TextView device_Ip_Port;

    ImageButton powerButton;
    ProgressDialog pd;
    User user;
    Handler connecthandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Log.d("handleMessage: ","接收成功");
            //根据获取的状态来判断当前插座的亮灭状态
            switch (msg.what){
                //是否用户连接成功
                case SocketClient.SOCKET_CONNTENTC:
                    socket_mode = SocketClient.SOCKET_CONNTENTC;
                    pd.dismiss();
                    //清除文本
                    userNameEdit.setText("");
                    userPasswordEdit.setText("");
                    device_Ip_Port.setText("当前连接地址: "+IP+":"+PORT);
                    connect_console.startAnimation(mHiddenAction);
                    connect_console.setVisibility(View.GONE);
                    connected_console.startAnimation(mShowAction);
                    connected_console.setVisibility(View.VISIBLE);
                    break;
                case SocketClient.SOCKET_BUTTON_STATUS:
                    socket_mode = SocketClient.SOCKET_BUTTON_STATUS;
                    String contentData = (String)msg.obj;
                    try {
                        JSONObject packetObject = new JSONObject(contentData);
                        JSONObject contentObject = packetObject.getJSONObject("result");
                        String status = contentObject.getString("status");
                        String id = contentObject.getString("id");
//                        if(id.equals(device_ID)){}
                        if(status.equals("O")){
                            button_mode = BUTTON_ON;
                            powerButton.setBackgroundResource(R.drawable.power_on);
                        }else if(status.equals("C")){
                            button_mode = BUTTON_OFF;
                            powerButton.setBackgroundResource(R.drawable.power_off);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
                case SocketClient.SOCKET_NOTCONNECT:
                    Toast.makeText(Main.this,"用户登陆失败",Toast.LENGTH_SHORT).show();
                    pd.dismiss();
                    break;
                case SocketClient.SOCKET_CHECK:
                    String content = (String)msg.obj;
                    Toast.makeText(Main.this,content,Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        mShowAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 1.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                0.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        mShowAction2 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                0.0f, Animation.RELATIVE_TO_SELF, -1.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                0.0f);
        mHiddenAction.setDuration(500);
        mShowAction.setDuration(500);
        mShowAction2.setDuration(500);
        toolbar = (Toolbar)findViewById(R.id.nav1_toolbar);
        setSupportActionBar(toolbar);
        initView();
        register();
        socket_mode = SocketClient.SOCKET_NOTCONNECT;
        button_mode = BUTTON_OFF;

        /**
         * StrictMode类是Android 2.3 （API 9）引入的一个工具类，
         * 可以用来帮助开发者发现代码中的一些不规范的问题，
         * 以达到提升应用响应能力的目的。举个例子来说，
         * 如果开发者在UI线程中进行了网络操作或者文件系统的操作，
         * 而这些缓慢的操作会严重影响应用的响应能力，甚至出现ANR对话框。
         * 为了在开发中发现这些容易忽略的问题，我们使用StrictMode，
         * 系统检测出主线程违例的情况并做出相应的反应，最终帮助开发者优化和改善代码逻辑。
         * 在主线程中实现网络请求
         */
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork()
                .penaltyLog()
                .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects()
                .penaltyLog()
                .penaltyDeath()
                .build());



    }



    private void initView(){
        connect_console=(LinearLayout)findViewById(R.id.connect_console);
        connected_console=(LinearLayout)findViewById(R.id.connected_console);
        device_console=(LinearLayout)findViewById(R.id.device_console);

        close_connect=(Button) findViewById(R.id.close_connect);
        bt_search = (Button)findViewById(R.id.search_app);
        ed_searchId = (EditText)findViewById(R.id.search_id);
        powerButton = (ImageButton)findViewById(R.id.power_bn);

        //登陆的用户名和密码
        userNameEdit = (EditText)findViewById(R.id.login_user_name);
        userPasswordEdit = (EditText)findViewById(R.id.login_user_password);
        delay_time=(EditText) findViewById(R.id.delay_time);
        open_delay=(Button) findViewById(R.id.open_delay);

        //用户连接
        connect=(Button)findViewById(R.id.connect);
        //用户注册
        login = (Button)findViewById(R.id.first_login);
        //设备相关数据
        device_ID = (TextView)findViewById(R.id.device_id);
        device_Ip_Port = (TextView)findViewById(R.id.device_ip);
    }

    private void register(){
        //用户注册
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(Main.this,RegisterActivity.class);
//                startActivity(intent);
                showRegisterDialog();
            }
        });
        //登陆连接
        connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userName = userNameEdit.getText().toString();
                String userPassword = userPasswordEdit.getText().toString();
                user = new User(userName,userPassword);
                String contentUser = new Gson().toJson(user);

                pd = ProgressDialog.show(Main.this,"登陆","加载中请等待..");
                //pd.setContentView(R.layout.dialog_logging_in);
                pd.show();

                try{
                    client = new SocketClient(IP,PORT);
                    if(client.isConnected()){
                        Log.d("sendMessage: ","连接数据成功");
                        client.sendMessage("id:"+String.valueOf(Utility.randomID()));
                        client.sendMessage(contentUser);
                        client.setHandler(connecthandler);
                        new Thread(client).start();
                    }
                }catch (SocketTimeoutException e){
                    e.printStackTrace();
                    Log.i("xfh", "getIp...SocketTimeoutException");
                    Toast.makeText(Main.this,"登陆失败，服务器连接超时",Toast.LENGTH_SHORT).show();
                    pd.dismiss();
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        });
        close_connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                connected_console.startAnimation(mHiddenAction);
                connected_console.setVisibility(View.GONE);
                connect_console.startAnimation(mShowAction);
                connect_console.setVisibility(View.VISIBLE);
                //关闭连接时，记得要把device_console设为invisible
                if(device_console.getVisibility()==View.VISIBLE) {
                    device_console.startAnimation(mHiddenAction);
                    device_console.setVisibility(View.INVISIBLE);
                }
            }
        });
        //设备id切换
        bt_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String id = ed_searchId.getText().toString();
                device_ID.setText("ID:"+id);
                //("to:"+id+":R");
                Log.d("onClick: ",id);
                try{
                    client.sendMessage(id);
                    client.sendMessage("to:"+id+":R");
//                    client.setHandler(connecthandler);
                    if(device_console.getVisibility()==View.INVISIBLE) {
                        device_console.startAnimation(mShowAction2);
                        device_console.setVisibility(View.VISIBLE);
                    }
//                    String str = client.reciveMessage();
//                    Log.d("run: ",str);
//                    if(str.equals("1")){
//                        Message msg = new Message();
//                        msg.what = 1;
//                        handler.sendMessage(msg);
//                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        });
        powerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Device device = new Device();
                device.setId(String.valueOf(ed_searchId.getText().toString()));
                if(socket_mode == SocketClient.SOCKET_NOTCONNECT){
                    Toast.makeText(Main.this,"没有连接对应的设备",Toast.LENGTH_SHORT).show();
                    return ;
                }
                if(socket_mode == SocketClient.SOCKET_BUTTON_STATUS || socket_mode == SocketClient.SOCKET_CONNTENTC) {
                    if (button_mode == BUTTON_ON) {
                        device.setStatus("C");
                        button_mode =BUTTON_OFF;
                        String contentCommand ="to:"+device.getId()+":C";
                        Toast.makeText(Main.this,contentCommand,Toast.LENGTH_SHORT).show();
                        client.sendMessage(contentCommand);
                        powerButton.setBackgroundResource(R.drawable.power_off);
                    } else if (button_mode == BUTTON_OFF) {
                        device.setStatus("O");
                        button_mode = BUTTON_ON;
                        String contentCommand ="to:"+device.getId()+":O";
                        Toast.makeText(Main.this,contentCommand,Toast.LENGTH_SHORT).show();
                        client.sendMessage(contentCommand);
                        powerButton.setBackgroundResource(R.drawable.power_on);
                    }
//                    if(button_mode == BUTTON_ON){
//                        powerButton.setBackgroundResource(R.drawable.power_on);
//                    }else if(button_mode == BUTTON_OFF){
//                        powerButton.setBackgroundResource(R.drawable.power_off);
//                    }
                }
                open_delay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int time= Integer.parseInt(delay_time.getText().toString());
                        Timer t=new Timer();
                        t.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                powerButton.callOnClick();
                            }
                        },time*1000);
                    }
                });
            }
        });

    }
    private void showRegisterDialog(){
        final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setView(this.getLayoutInflater().inflate(R.layout.activity_register,null));
        dialog.show();
    }
    public boolean isfirst = true;
    public boolean onKeyDown(int keyCode,KeyEvent event){
        int progress;
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (connected_console.getVisibility() == View.VISIBLE){
                    client.close();
                    close_connect.callOnClick();
                }else {
                    Toast.makeText(Main.this,"返回",Toast.LENGTH_SHORT).show();
                    if(pd != null)
                        pd.dismiss();
                    if(isfirst){
                        isfirst = false;
                        Toast.makeText(this,"再按一次退出程序",Toast.LENGTH_SHORT).show();
                        new Timer().schedule(new TimerTask() {
                            @Override
                            public void run() {
                                isfirst = true;
                            }
                        },2000);
                        return true;
                    }else{
                        client.close();
                        this.finish();
                        System.exit(0);
                    }
                }
                break;
        }
        return false;
    }
}
